package StudyCode.summary.myfile;

import java.io.IOException;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class LockWithCompletionHandler {
	private static Thread current;

	public static void main(String[] args) {
		Path path = Paths.get("E:\\迅雷下载\\test1.txt");
		try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
				.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE)) {
			current = Thread.currentThread();
			asynchronousFileChannel.lock("锁定操作状态:",
					new CompletionHandler<FileLock, Object>() {
						@Override
						public void completed(FileLock result, Object attachment) {
							System.out.println(attachment + " " + result.isValid());
							if (result.isValid()) {
								try {
									result.release();
								} catch (IOException ex) {
									System.err.println(ex);
								}
							}
							current.interrupt();
						}

						@Override
						public void failed(Throwable exc, Object attachment) {
							System.out.println(attachment);
							System.out.println("错误:" + exc);
							current.interrupt();
						}
					});

			System.out.println("等待中... \n");
			try {
				current.join();
			} catch (InterruptedException ignored) {
			}
			System.out.println("执行完毕");

		} catch (Exception ex) {
			System.err.println(ex);
		}
	}
}
